import React, { useEffect, useState, memo, useRef } from 'react';

import styles from './style.less';
import { RightOutlined, EllipsisOutlined } from '@ant-design/icons';
import { Card, Tooltip, message, Popconfirm, Menu, Dropdown } from 'antd';
import Icon from '@/components/Icon';

import {
  dashboardWidgetsItem,
  IChartConfig,
  IChartDataFilterConfigs,
  DataRecord,
} from '@/pages/SelfQuery/type';
import { ConnectState } from '@/models/connect';

import { IResponse } from '@/models/connect';

import { connect, Dispatch } from 'umi';

import CombinedChart from '../Charts';

const classnames = require('classnames');

interface WidgetBoardProps {
  widget: dashboardWidgetsItem;
  dispatch: Dispatch;
  loading?: boolean;
  editing?: boolean;
  manage?: boolean;
  removeWidgets?: (id: number) => void;
  className?: any
  filterControl?: (viewId?: number, model?: any, widgetId?: number) => any
}

export const computeWidth = (node: any) => {
  const totalWidth = parseInt(getComputedStyle(node).width, 10);
  const padding =
    parseInt(getComputedStyle(node).paddingLeft, 10) +
    parseInt(getComputedStyle(node).paddingRight, 10);
  return totalWidth - padding;
};
const WidgetBoard: React.FC<WidgetBoardProps> = memo((props) => {
  const { widget, dispatch, editing, manage, removeWidgets, className, filterControl } = props;
  const [dataRecord, setDataRecord] = useState<DataRecord>({ resultList: null, columns: [] }); // 数据集合
  const [filterConfigs, setFilterConfigs] = useState<any>({}); // 封装过滤数据的条件（用于下钻）
  const [configs, setConfigs] = useState<any>(null); // 图表配置
  const [subscribe, setSubscribe] = useState<any>(null); // 该指标是否已订阅
  const [cardLoading, setCardLoading] = useState<boolean>(false); // 加载状态
  const widgetBoardBodyRel: any = useRef();

  // 点击选中的指标显示详情
  const showIndexDetail = () => {
    dispatch({
      type: 'widget/fetchIndexDetail',
      payload: {
        dataRecord,
        configs,
        filterConfigs,
        widget,
        subscribe,
      },
    });

    // 查看详情 滚动条回到顶部
    if (document.getElementById('root')) {
      const dom = document.getElementById('root');
      dom && dom.scrollIntoView();
    }
  };

  // 取消订阅指标
  const clearSubscribe = () => {
    dispatch({
      type: 'widget/canelSubscribeWidget',
      payload: { widgetId: widget.widgetId },
      callback: (res: IResponse) => {
        const { header } = res;
        if (header && header.code === 200) {
          message.success('取消订阅成功');
          // 重新获取订阅列表
          dispatch({
            type: 'subscribe/fetchSubscribeWidgets',
          });
        }
      },
    });
  };
  useEffect(() => {
    loadData();

    // clearTimeout(filterTime)
    // filterTime = setTimeout(()=>{
    //   loadData()
    // },2000)
  }, [filterControl && filterControl()]);
  useEffect(() => {
    // loadData();
  }, []);
  const loadData = () => {
    // 获得 获取指标图表数据所需参数
    setCardLoading(true);
    dispatch({
      type: 'panel/fetchWidgetParams',
      payload: { id: widget.widgetId },
      callback: (response: IResponse) => {
        const { header, payload } = response;
        if (header.code === 200) {
          // 请求参数转换
          const config: IChartConfig = JSON.parse(payload.config);
          const { metrics, model } = config;
          const { viewId } = payload;
          let filters = config.filters.map((filter: any) => filter.config.sqlModel[0]);

          if (filterControl) {
            const val = filterControl(viewId, model, widget.id);
            filters = [...filters, ...val];
          }
          let body: IChartDataFilterConfigs = {
            groups: config.cols.map((v: any) => v.name),
            aggregators: [],
            filters,
            orders: config.orders,
            pageNo: 0,
            pageSize: 0,
            nativeQuery: false,
            cache: config.cache,
            expired: config.expired,
            flush: false,
          };
          let aggregators: Array<any> = [];
          metrics.forEach((metric) => {
            let aggregator = {
              column: metric.name.split('@')[0],
              func: metric.agg,
              calculate: metric.calculate,
            };
            if (metric.totalType !== 'cancel') {
              // @ts-ignore
              aggregator.totalType = metric.totalType;
            }
            aggregators.push(aggregator);
          });
          body.aggregators = aggregators;

          // 富文本类型，不请求数据
          if (config.selectedChart === 15) {
            setCardLoading(false);
            return;
          }

          // 请求图表数据
          dispatch({
            type: 'panel/fetchWidgetData',
            payload: { id: viewId, body: JSON.stringify(body) },
            callback: (res: IResponse) => {
              const { header, payload: dataRecord } = res;
              if (header && header.code === 200) {
                if (!dataRecord) {
                  setDataRecord({ resultList: [], columns: [] });
                  return;
                }
                setDataRecord(dataRecord);
                setFilterConfigs(body);
                setSubscribe(payload.isSubscribe);

                if (Object.keys(dataRecord).length > 0) {
                  setConfigs(JSON.parse(response.payload.config));
                }
              }
              setCardLoading(false);
            },
          });
        }
      },
    });
  };
  const menu = (
    <Menu>
      {dataRecord.resultList && dataRecord.resultList.length && <Menu.Item onClick={showIndexDetail}>查看更多</Menu.Item>}
      {/* @ts-ignore */}
      <Menu.Item onClick={() => {
        removeWidgets(widget.widgetId);
      }}>删除</Menu.Item>
    </Menu>
  );
  return (
    <div className={classnames({
      [styles.widgetBoardBody]: true,
      className,
    })}
         ref={widgetBoardBodyRel}
         style={{ height: 300 }}
    >
      <Card
        size='small'
        type='inner'
        title={widget.widgetName}
        extra={
          editing ? (
            <Popconfirm
              placement='topRight'
              title='确定取消订阅该指标吗？'
              onConfirm={clearSubscribe}
              okText='确定'
              cancelText='取消'
            >
              <span className={styles.more}>
                <Icon type='deletes' width={20} height={20} />
              </span>
            </Popconfirm>
          ) : dataRecord.resultList && dataRecord.resultList.length && !manage ? (
            <Tooltip title='点击查看更多'>
              <RightOutlined className={styles.more} onClick={showIndexDetail} />
            </Tooltip>
          ) : manage ? (
            <Dropdown overlay={menu}>
              <EllipsisOutlined className={styles.more} style={{ fontSize: '20px' }} />
            </Dropdown>
          ) : (
            ''
          )
        }
        style={{ minHeight: 194 }}
        loading={cardLoading}
      >
        <CombinedChart
          data={dataRecord.resultList}
          columns={dataRecord.columns}
          totalDatas={dataRecord.totalDatas}
          configs={configs}
          width={500}
          height={300}
          filterConfigs={filterConfigs}
          name={widget.widgetName}
        />
      </Card>
    </div>
  );
});

export default connect(({ loading }: ConnectState) => ({
  loading: loading.effects['panel/fetchWidgetData'],
}))(WidgetBoard);
